from PyQt4.QtGui import QWidget,QVBoxLayout,QTransform
from PyQt4 import QtCore,QtGui,QtOpenGL,Qt
from KCharts.KGraphics import KGraphicsScene,KGraphicsView
from random import randint, shuffle
from KIndicators import *
import importlib
import imp
class KSingleChartWidget(QWidget):
	'''
	The widget to show a single chart, it contains a graphicsscene, a graphicsview. 
	'''

	ContextMenuClicked=Qt.pyqtSignal(str)	
	def __init__(self, parent,stockobject):
		super(KSingleChartWidget, self).__init__(parent)
		self.m_stock=stockobject # get stock object to display
		
		# setup scene 
		self.scene=KGraphicsScene.KGraphicsScene(self,stockobject)
		self.scene.setSceneRect(0,0,self.width(),self.height())
		self.ContextMenuClicked.connect(parent.OnContextMenuClicked) # inform KChartsWidget
		self.scene.CreateInitialViewModels()


		
		# setup view
		self.view=KGraphicsView.KGraphicsView(self.scene)
		mtransform=QTransform().scale(0.95,0.95)
		self.view.setTransform(mtransform)

		#self.view.setViewport(QtOpenGL.QGLWidget())
				 
		# setup layout
		self.mLayout=QVBoxLayout(self)
		self.mLayout.setContentsMargins(0,0,0,0) # set blank space between outside of layout and its parent widget		
		self.mLayout.setSpacing(0)	
		self.mLayout.addWidget(self.view)
		self.setMinimumWidth(500)
		self.setMinimumHeight(400)


	def UpdateIndicator(self,paradict):
		# update indicator for this chart, trigger when indicator tree selection is changed
		
		selected=paradict['checkstatus']
		if selected==True: # adding new indicator item
			
			(modulename,classname)=str(paradict['class']).rsplit('.',1)
			pMod =  importlib.import_module(modulename)
			IndicatorClass= getattr(pMod, classname) #load indicator class
	
			(dispmodulename,dispclassname)=str(paradict['viewclass']).rsplit('.',1)
			pMod =  importlib.import_module(dispmodulename)
			IndicatorDisplayClass= getattr(pMod, dispclassname) #load indicator display class
		
			viewname=str(paradict['windowname'])
			viewmodelobj=self.scene.GetViewByName(viewname)
			
			if viewmodelobj:
				featureitem=IndicatorDisplayClass(viewmodelobj,self.m_stock)			
				eindicator=IndicatorClass(self.m_stock)
				eindicator.calculate()
				featureitem.SetModel(eindicator)	
				self.scene.AddDisplayItem(dispmodulename,featureitem)
				
		else: # remove indicator item
			(dispmodulename,dispclassname)=str(paradict['viewclass']).rsplit('.',1)
			self.scene.RemoveDisplayItem(dispmodulename)
			
			

		

		
	def resizeEvent(self,evt):
		# adjust scene rect when resized
		self.scene.setSceneRect(0,0,self.width(),self.height())
		#self.UpdateDisplay()
		
	def UpdateDisplay(self):
		# call this function whenever you want to widget content to refresh
		self.scene.update(self.scene.sceneRect())
		
		#self.view.viewport().update()


		

